package 多线程.管程法;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author by zhangleishuidihuzhu.com
 * @Date 2023/5/20 18:52
 */
public class LinkedBlockTest {

    public static void main(String[] args) {
        AtomicInteger i = new AtomicInteger(0);
        LinkedBlockingQueue<Chicken> list = new LinkedBlockingQueue<>(10);

        for (int i1 = 0; i1 < 10; i1++) {
            new Thread(new Producer1(list, i)).start();
        }
//        new Thread(new Producer1(list, i)).start();
//        new Thread(new Producer1(list, i)).start();

        new Thread(new Consumer1(list)).start();

//        ExecutorService producer = Executors.newFixedThreadPool(3);
//        for (int i = 0; i < 1000; i++) {
//            producer.submit(new Producer1(list))
//        }
//
//        ExecutorService consumer = Executors.newFixedThreadPool(3);


    }



    public static class Producer1 implements Runnable{

        private AtomicInteger i;

        private LinkedBlockingQueue<Chicken> linkedBlockingQueue;

        public Producer1(LinkedBlockingQueue linkedBlockingQueue, AtomicInteger i) {
            this.linkedBlockingQueue = linkedBlockingQueue;
            this.i = i;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int cur = i.getAndIncrement();
                linkedBlockingQueue.add(new Chicken(cur));
                System.out.println(Thread.currentThread().getId() +"======" + "开始生产第"+cur+"只🐔" +"，当前数量为"+linkedBlockingQueue.size());
            }
        }
    }

    public static class Consumer1 implements Runnable{

        private LinkedBlockingQueue<Chicken> linkedBlockingQueue;

        public Consumer1(LinkedBlockingQueue linkedBlockingQueue) {
            this.linkedBlockingQueue = linkedBlockingQueue;
        }


        @Override
        public void run() {
            while (true) {
                if(linkedBlockingQueue.size() == 0) {
//                    try {
////                        Thread.sleep(1000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                    continue;
                }
                int size = linkedBlockingQueue.size();
                Chicken c = linkedBlockingQueue.poll();
                System.out.println(Thread.currentThread().getId() +": 开始消费第"+ c.getId() +"只🐔" +"，当前数量为"+size);
            }
        }
    }

    static class Chicken{
        private Integer id;
        public Chicken(Integer id) {
            this.id = id;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }
    }


}
